//
//  CCNetwork.m
//  CCFC_IPHONE
//
//  Created by 陈曦 xichen2 on 10-11-1.
//  Copyright 2010 iFLYTEK. All rights reserved.
//
#include "CCAll.h"

#ifdef	OBJC_MACRO
#import <sys/socket.h>
#import <netinet/in.h>
#import <arpa/inet.h>
#import <netdb.h>
#import <SystemConfiguration/SCNetworkReachability.h>

#import "CCNetwork.h"


@implementation CCNetwork

/*
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{

}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
	[];
}
*/

+ (NSURLConnection *)startNetworkStatusTest:(NSString *)url withDelegate:(id)delegate
{
	//创建NSMutableURLRequest对象
	NSString *urlString = nil;
	
	if(!url)
	{
		urlString = @"http://8.8.8.8";
	}
	else
	{
		urlString = [NSString stringWithString:url];
	}
	LOG("startNetworkStatusTest will connect to url: %@", urlString);
	
	NSURL *nsUrl = CREATE_URL(urlString);
	NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:nsUrl];
	
	//创建连接并启动
	NSURLConnection *conn = [[[NSURLConnection alloc] 
							 initWithRequest:request 
							 delegate:delegate 
							 startImmediately:TRUE] autorelease];
	[conn start];
	
	return conn;
}

//官方提供的测试网络状态是否正常代码：NB. 在iPhone3上存在bug
+ (BOOL)isConnectedToNetwork
{
	// Create zero addy
	struct sockaddr_in zeroAddress;
	bzero(&zeroAddress, sizeof(zeroAddress));
	zeroAddress.sin_len = sizeof(zeroAddress);
	zeroAddress.sin_family = AF_INET;
	
	// Recover reachability flags
	SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
	SCNetworkReachabilityFlags flags;
	
	BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
	CFRelease(defaultRouteReachability);
	
	if (!didRetrieveFlags)
	{
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Warning!" message:@"No Internet." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[alert show];
		[alert release];
	}
	
	BOOL isReachable = flags & kSCNetworkFlagsReachable;
	BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
	return (isReachable && !needsConnection) ? YES : NO;
	
}

@end

#endif	//OBJC_MACRO
